# 实现获取用户信息视图函数
from flask import g
from flask_restful import Resource
from sqlalchemy.orm import load_only
from app import db
from utils.parser import image_file
from utils.img_storage import upload_file
from flask_restful.reqparse import RequestParser
from flask import current_app
from models.user import User
from utils.decorators import login_required
from cache.user import UserCache


class CurrentUserResource(Resource):
    """个人中心-当前用户"""
    # 通过method_decorators类属性来设置类视图的装饰器
    # 列表形式 所有请求方式都会使用
    # 字典形式 给请求方式分别设置装饰器
    method_decorators = {'get': [login_required]}

    def get(self):
        # 获取用户id
        userid = g.userid

        # 查询用户数据
        # user = User.query.options(
        #     load_only(User.id, User.name, User.profile_photo, User.introduction, User.article_count,
        #               User.following_count, User.fans_count)).filter(User.id == userid).first()
        #
        # # 序列化返回数据
        # return user.to_dict()
        # 修改 获取用户信息 和 修改头像 视图函数
        # 查询用户数据
        user_cache = UserCache(userid).get()
        if user_cache:
            return user_cache
        else:
            return {'message': "Invalid User", 'data': None}, 400


class UserPhotoResource(Resource):
    method_decorators = [login_required]

    def patch(self):
        """修改头像"""
        # 获取参数
        userid = g.userid
        parser = RequestParser()
        parser.add_argument('photo', required=True, type=image_file, location='files')
        args = parser.parse_args()
        img_file = args.photo

        # f = request.files.get('photo')
        # f.save()
        # f.read()

        # 读取二进制数据
        img_bytes = img_file.read()

        # 上传到七牛云
        try:
            file_url = upload_file(img_bytes)
        except BaseException as e:
            return {'message': 'Thired Error: %s' % e, 'data': None}, 500

        # 将数据库中头像URL进行更新
        User.query.filter(User.id == userid).update({'profile_photo': file_url})
        db.session.commit()

        # 将数据对象删除
        usercache = UserCache(userid)
        usercache.clear()

        # 返回URL
        return {'photo_url': file_url}
